'use strict';

const mongoose = require('mongoose'),
    foodAdModel = mongoose.model('FoodAd');
const http = require('http');
var querystring = require('querystring');

module.exports = {
    createFoodAdByMerchant: createFoodAdByMerchant, 
    getFoodAdByMerchant: getFoodAdByMerchant,
    foodAdUpdateStatus: foodAdUpdateStatus,
    getPassedFoodAd: getPassedFoodAd,
    getUnpassedFoodAd: getUnpassedFoodAd,
}


function createFoodAdByMerchant(foodAd,callback){
      
    let data = {
        food:foodAd.food.fname,
        price:foodAd.food.fprice,
        merchant:foodAd.merchant.icnum,
        picUrl:foodAd.food.fimg  
    };
    let content = querystring.stringify(data);
    let contentLen = Buffer.byteLength(content, 'utf8');

     let option = {
         host:'10.222.29.185',
         port:8999,
         path: '/a/advert/add',
         method: 'POST',
         headers: {
               'Content-Type': 'application/x-www-form-urlencoded',
               'Content-Length': contentLen
               }
       };

    let req = http.request(option,function(res){
         console.log("statusCode: ", res.statusCode);
         console.log("headers: ", res.headers);
         let _data='';
        res.on('data', function(chunk){
             _data += chunk;
          });
        res.on('end', function(){
        });
    });
      req.write(content);
      req.end();
    foodAdModel.create(foodAd,function(error,data){
        callback(null,data);
    });
}


function getFoodAdByMerchant(icnum,callback){
    foodAdModel.find({'merchant.icnum': icnum},function(err,doc){
       callback(null,doc);
    });

} 

function getUnpassedFoodAd(icnum,callback){
    foodAdModel.find({'merchant.icnum': icnum,status:'0'},function(err,doc){
       callback(null,doc);
    });

} 

function getPassedFoodAd(icnum,callback){
    foodAdModel.find({'merchant.icnum': icnum,status:'1'},function(err,doc){
       callback(null,doc);
    });

}


function foodAdUpdateStatus(food,icnum,status,callback){
    if(status == "1"){
        foodAdModel.updateOne({'food.fname':food,'merchant.icnum':icnum},{
           status : status
        },function(err, doc){
            callback(null,doc);
        });
    }
    else{
        foodAdModel.updateOne({'food.fname':food,'merchant.icnum':icnum},{
           status : "0"
        },function(err, doc){
            callback(null,doc);
        });        
    }
    


}